<!--导入css-->
<!-- Bootstrap -->
<link href="cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link href="/plugin/nprogress/nprogress.css" rel="stylesheet">
<!-- iCheck -->
<link href="/plugin/iCheck/skins/flat/green.css" rel="stylesheet">
<!-- Datatables -->
<link href="/plugin/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">
<link href="/plugin/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet">
<link href="/plugin/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet">
<link href="/plugin/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet">
<link href="/plugin/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet">

<div class="right_col" role="main">
    <div class="">
        <div class="page-title">
            <div class="title_left">
                <h3>Roles <small>Role List</small></h3>
            </div>
        </div>

        <div class="clearfix"></div>

        <div class="row">
            <div class="col-md-12 col-sm-12 ">
                <div class="x_panel">
                    <div class="x_title">
                        <ul class="nav navbar-right panel_toolbox" style="margin-left:0; float: left;">
                            <button id="addRoleBtn" type="button" class="btn btn-primary"
                                    data-toggle="modal" data-target="#addRoleModal">Add</button>
                        </ul>
                        <div class="clearfix"></div>
                    </div>
                    <div class="x_content">
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="card-box table-responsive">
                                <table id="datatable" class="table table-striped table-bordered" style="width:100%">
                                    <thead>
                                        <tr>
                                            <th>RoleId</th>
                                            <th>UserName</th>
                                            <th>Operation</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
               </div>
            </div>
        </div>
    </div>
    </div>
</div>

<!--引入模态框的html文件-->
<div th:replace="account/roleAdd"></div>
<div th:replace="account/roleEdit"></div>

<!--导入js-->
<!-- FastClick -->
<script src="/plugin/fastclick/lib/fastclick.js"></script>
<!-- NProgress -->
<script src="/plugin/nprogress/nprogress.js"></script>
<!-- iCheck -->
<script src="/plugin/iCheck/icheck.min.js"></script>
<!-- Datatables -->
<script src="/plugin/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/plugin/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<script src="/plugin/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
<script src="/plugin/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script>
<script src="/plugin/datatables.net-buttons/js/buttons.flash.min.js"></script>
<script src="/plugin/datatables.net-buttons/js/buttons.html5.min.js"></script>
<script src="/plugin/datatables.net-buttons/js/buttons.print.min.js"></script>
<script src="/plugin/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js"></script>
<script src="/plugin/datatables.net-keytable/js/dataTables.keyTable.min.js"></script>
<script src="/plugin/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
<script src="/plugin/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
<script src="/plugin/datatables.net-scroller/js/dataTables.scroller.min.js"></script>


<script type="text/javascript">
    var DEFAULT_PAGE_SIZE = 3;
    $(document).ready(function() {
        initRoleTable(DEFAULT_PAGE_SIZE);

        $("#addRoleBtn").bind("click", function() {
            intAddModal();
        });
        $("#insertRoleBtn").bind("click", function() {
            addRole();
        });
        $("#editRoleBtn").bind("click", function() {
            editRole();
        });
    });
    //渲染表格
    function initRoleTable(pageSize) {
        $('#datatable').DataTable({
            'paging': true, //分页
            "serverSide": true, //开启后端分页
            "pagingType": "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
            "pageLength": pageSize, //定义初始的页长
            "processing": true,
            "destroy": true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
            'lengthChange': true, //控制是否能够调整每页的条数
            'searching': true,
            'data-show-refresh': true,
            'ordering': true,
            'autoWidth': false,
            "ajax": function (data, callback, settings) {
                // 从data获取查询数据
                var columIndex = data.order[0].column;
                var sort = data.order[0].dir;
                var orderBy = data.columns[columIndex].name;
                pageSize = data.length == undefined  ? pageSize : data.length;

                var searchVo = {};
                searchVo.currentPage = (data.start / pageSize) + 1;
                searchVo.pageSize = pageSize;
                searchVo.orderBy = orderBy;
                searchVo.sort = sort;
                searchVo.keyWord = data.search.value;

                $.ajax({
                    url : "/api/roles",
                    type : "post",
                    contentType: "application/json",
                    data : JSON.stringify(searchVo),
                    success : function (rs) {
                        //整个表格的数据结构
                        var fData = {
                            draw :0,//画几行
                            recordsTotal: 0,//分页总条数
                            recordsFiltered: 0,//使用过滤器的总条数
                            data: []//将行内数据设置到data
                        };
                        if (!rs) {
                            layer.alert("请求出错，请稍后重试" + rs.errmsg, {icon: 2});
                            callback(fData);
                            return;
                        };
                        if (rs.list == null) {
                            $('#datatable tbody tr').remove();
                            $('#loading').remove();
                            callback(fData);
                            return;
                        }
                        $('#loading').remove();
                        var gearDatas = [];
                        for (var i = 0; i < rs.list.length; i++) {
                            //包装行数据
                            var rowData = new TData(rs.list[i].roleId, rs.list[i].roleName);
                            // 将行数据放到数组里
                            gearDatas.push(rowData);
                        }
                        fData.data = gearDatas;
                        fData.recordsTotal = rs.total;
                        fData.recordsFiltered = rs.total;
                        callback(fData);
                    },
                    error : function (data) {
                        layer.alert(data.responseText, {icon: 0});
                    }
                });
            },
            "columns": [ //定义行数据字段
                //data是ajax返回数据的属性，name是每一列包装好的列名，sorttable是否支持排序
                {data: 'roleId', name: "role_id", sortable: true},
                {data: 'roleName', name: "role_name", sortable: true},
                {data: 'operate', width: '80px', sortable: false}
            ]
        });
    }
    //行数据结构
    function TData(roleId, roleName) {
        this.roleId = roleId;
        this.roleName = roleName;
        this.operate = function () {
            return "<a href='#' class='btn_editcolor' data-toggle='modal' data-target='#roleEditModal' " +
                "onclick='initEditModal(\"" + roleId + "\")'>编辑</a>&nbsp;" +
                "<a href='javascript:void(0);' onclick='deleteRole(\"" + roleId + "\")' class='btn_editcolor'>删除</a>";
        }
    }

    //置空模态框的值，并调用custom.js中的方法
    function intAddModal() {
        $("#roleNameForAddPage").val("");
    }

    //增加角色方法
    function addRole() {
        var role = {};
        role.roleName = $("#roleNameForAddPage").val();
        $.ajax({
            url : "/api/role",
            type : "post",
            contentType: "application/json",
            data : JSON.stringify(role),
            success : function (rs) {
                if (rs.status == 200) {
                    initRoleTable(DEFAULT_PAGE_SIZE);
                } else {
                    layer.alert(rs.messgae, {icon: 0});
                }
            },
            error : function (data) {
                layer.alert(data.responseText, {icon: 0});
            }
        });
    }

    //初始化编辑模态框
    function initEditModal(roleId){
        $.ajax({
            url : "/api/role/" + roleId,
            type : "get",
            success : function (rs) {
                $("#roleIdForEditPage").val(rs.roleId);
                $("#roleNameForEditPage").val(rs.roleName);
            },
            error : function (data) {
                layer.alert(data.responseText, {icon: 0});
            }
        });
    }

    //修改角色
    function editRole(){
        //包装数据
        var role = {};
        role.roleId = $("#roleIdForEditPage").val();
        role.roleName = $("#roleNameForEditPage").val();
        //ajax请求交互数据
        $.ajax({
            url : "/api/role",
            type : "put",
            contentType: "application/json",
            data : JSON.stringify(role),
            success : function (rs) {
                if (rs.status == 200) {
                    initRoleTable(DEFAULT_PAGE_SIZE);
                } else {
                    layer.alert(rs.messgae, {icon: 0});
                }
            },
            error : function (data) {
                layer.alert(data.responseText, {icon: 0});
            }
        });
    }

    //删除
    function deleteRole(roleId) {
        bootbox.confirm("Are you sure?", function(result) {
            if(result) {
                $.ajax({
                    url : "/api/role/" + roleId,
                    type : "delete",
                    success : function (data) {
                        if (data.status == 200) {
                            initRoleTable(DEFAULT_PAGE_SIZE);
                        } else {
                            // window.location.href = data.object;
                            layer.msg(data.message, {icon: 0});
                        }
                    },
                    error : function (data) {
                        layer.msg(data.responseText, {icon: 0});
                    }
                });
            }
        });
    }

</script>